package com.htfyun.factorytest;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.VolumeUtils;
import com.htfyun.eink.BuildConfig;
import com.htfyun.factorytest.agingtest.AgingTestItemAttr;
import com.htfyun.factorytest.agingtest.AgingTestItemBase;
import com.htfyun.factorytest.common.BatteryCurrentThresholdEnum;
import com.htfyun.factorytest.common.BatteryInfo;
import com.htfyun.factorytest.common.Constants;
import com.htfyun.factorytest.common.FTUtils;
import com.htfyun.factorytest.common.LedCtrl_PX30;
import com.htfyun.factorytest.common.PermissionManager;
import com.htfyun.factorytest.common.StandbyUtil;
import com.htfyun.factorytest.config.EinkProperty;
import com.htfyun.factorytest.config.HtfyunBuildConfig;
import com.htfyun.factorytest.config.PCCommand;
import com.htfyun.factorytest.device.DeviceAttr;
import com.htfyun.factorytest.utils.ArmFreqUtils;
import com.htfyun.factorytest.utils.DebugLog;
import com.htfyun.factorytest.utils.SystemPropertyUtil;
import com.htfyun.factorytest.utils.UsefulUtils;
import com.htfyun.factorytest.utils.WakeLockUtil;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;


public class AgingTestActivity extends SingleTestBaseActivity {

    private final static int FLAG_KEY_DOWN_POWER = 0x1;
    private final static int FLAG_KEY_DOWN_HOME = 0x2;
    private int flagKeyExit = FLAG_KEY_DOWN_POWER | FLAG_KEY_DOWN_HOME;
    private int flagKeyDown = 0;

    private Context mContext;

    private List<AgingTestItemBase> agingTestItemList = new ArrayList<>();

    private MyHandler myHandler;

    private BatteryInfo batteryInfo;

    private LinearLayout mLayoutTxt;
    private final static int COUNTS = 5;// 点击次数
    private final static long DURATION = 3000;
    private long[] mHits = new long[COUNTS];

    private TextView txtTemperature;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //设置窗体始终点亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_aging);

        mContext = this;

        mLayoutTxt = findViewById(R.id.layoutTxt);
        mLayoutTxt.setOnClickListener(v -> doubleClick());

        WakeLockUtil.disableAutoPowerOff(mContext);

        TextView txtMoreInfo = findViewById(R.id.txtMoreInfo);
        if (txtMoreInfo != null) {
            String appVersion = getString(R.string.app_version, UsefulUtils.getAppVersion(mContext) + "-" + BuildConfig.BUILD_TYPE);
            String serialNo = getString(R.string.serialno, EinkProperty.getSerialNumber());
            txtMoreInfo.setText(String.format("%s\n%s", appVersion, serialNo));
        }

        txtTemperature = findViewById(R.id.txtTemperature);

        myHandler = new MyHandler(this);

        View itemViewContainer = findViewById(R.id.itemViewContainer);

        for (AgingTestItemAttr attr : AgingTestItemAttr.values()) {
//            if (attr == AgingTestItemAttr.hardware) {
            agingTestItemList.add(attr.getAgingTestItem(mContext, itemViewContainer));
//            }
        }

        Collections.sort(agingTestItemList);

        updateTxtTips();

        for (int i = 0; i < agingTestItemList.size(); i++) {
            AgingTestItemBase itemBase = agingTestItemList.get(i);
            if (itemBase.getAgingTestItemAttr() != null) {
                DebugLog.e("item = " + itemBase.getAgingTestItemAttr().getName());
            }
        }

        if (!RootApplication.isExistHomeKey) {
            flagKeyExit &= ~FLAG_KEY_DOWN_HOME;
        }

//        bindService();

        initPermission();

        setStateEnabledAndInitStartTimeAbsolute();

        myHandler.sendEmptyMessageDelayed(MyHandler.MSG_TIME_TICK, MyHandler.PERIOD_TIME_TICK);

        batteryInfo = new BatteryInfo(this);

        //enable charging-sleep
        startChargingSleep();

        if (SystemProperties.getBoolean(Constants.SYS_NEED_CHECK, true)) {
            SystemPropertyUtil.setSystemProperty(Constants.SYS_NEED_CHECK, "false");
            if (AgingTestItemAttr.isAbnormalShutdown()) {
                int count = AgingTestItemAttr.getAbnormalShutdownCount(mContext);
                DebugLog.d("abnormal shutdown count = " + count);
                AgingTestItemAttr.setAbnormalShutdownCount(mContext, ++count);
            }
            SystemPropertyUtil.setSystemProperty(Constants.PERSIST_SYS_SHUTDOWN, "crash");
        }

    }

    private String buildAgingTestTips() {

        StringBuilder sb = new StringBuilder();
        for (AgingTestItemBase itemBase : agingTestItemList) {
            if (itemBase.getAgingTestItemAttr() == null) {
                continue;
            }
            sb.append(itemBase.getAgingTestItemAttr().getId());
            sb.append(". ");
            sb.append(itemBase.getAgingTestItemAttr().getDetail(mContext));
        }
        return RootApplication.isExistHomeKey ? getString(R.string.aging_test_info, sb.toString()) : getString(R.string.aging_test_info_no_home, sb.toString());

    }


    @Override
    public void startActivityFromChild(@NonNull Activity child, Intent intent, int requestCode) {
        super.startActivityFromChild(child, intent, requestCode);
    }

    @Override
    protected void onResume() {
        super.onResume();

        DebugLog.e("onResume");

        EinkProperty.setEinkFactoryTestEnabled(true);
//        EinkUtils.setCpuFreq(mContext, EinkUtils.CPU_FREQ_LEVEL_MAX, true);
        ArmFreqUtils.setCpuFreqMax();

        FTFloatWindowService.setFloatLayoutShow(false);

        startLedCtrl();
//        startTemperatureCheck();

        registerReceiver();

        batteryInfo.setOnBatteryChangedListener(onBatteryChangedListener);
        batteryInfo.startMonitor();

    }

    private void startChargingSleep() {
        DebugLog.e("enable charging sleep");
        LedCtrl_PX30.setLed("a");
        LedCtrl_PX30.setLed("s");
    }


    @Override
    protected void onPause() {
        super.onPause();

        DebugLog.e("onPause");

        EinkProperty.setEinkFactoryTestEnabled(false);
//        EinkUtils.resetCpuFreqParam(mContext);

        dismissDialog();

        FTFloatWindowService.setFloatLayoutShow(true);

        unregisterReceiver();

        batteryInfo.setOnBatteryChangedListener(null);
        batteryInfo.stopMonitor();

        dismissDialogWhenChargeCurrentFailed();
        dismissDialogWhenChargeUnplug();

        stopLedCtrl();
//        stopTemperatureCheck();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EinkProperty.setEinkFactoryTestEnabled(false);

        DebugLog.e("onDestroy");

        doDestroy();

        stopChargingSleep();

    }

    private void stopChargingSleep() {
        DebugLog.e("disable charging sleep");
        LedCtrl_PX30.setLed("A");
        LedCtrl_PX30.setLed("S");
    }

    private volatile boolean isDestroy = false;

    private synchronized void doDestroy() {

        if (isDestroy) {
            return;
        }

        isDestroy = true;

        DebugLog.e("doDestroy");

        stopLedCtrl();
        //reset STREAM_MUSIC
        resetStreamVolume();
//        stopTemperatureCheck();

        myHandler.removeMessages(MyHandler.MSG_TIME_TICK);

        for (AgingTestItemBase item : agingTestItemList) {
            item.stopTest();
        }
        agingTestItemList.clear();
    }

    private void resetStreamVolume() {
        VolumeUtils.setVolume(AudioManager.STREAM_MUSIC, Constants.AGING_VOLUME, 0);
        SystemProperties.set(Constants.FT_AGING_MUTE, "false");
    }


    private void periodicCheckItemTest() {

        if (AgingTestItemAttr.emmc_cpu.isTestOver(mContext)
                && !AgingTestItemAttr.isEmmcCpuTestOK(mContext)) {

            //如果emmc cpu 测试失败, 就直接返回了
            exitAging(true);
            return;
        }

        startAgingItemTest();
    }

    private void startAgingItemTest() {

        AgingTestItemBase item = null;

        for (AgingTestItemBase testItem : agingTestItemList) {
            if (testItem.getAgingTestItemAttr() == null) {
                continue;
            }

            if (testItem.getAgingTestItemAttr().isTestOver(mContext)) {

                if (testItem.isTestStarted()) {
                    testItem.stopTest();
                }

            } else if (item == null) {

                item = testItem;
            }
        }

        if (item == null) {
            //测试完了.
            exitAging(true);

        } else if (!item.isTestStarted()) {

            item.startTest();
            updateCurrentTestItemInfo(getString(R.string.aging_test_item_current, item.getAgingTestItemAttr().getNominalName(mContext)));
        }
    }

    private void updateCurrentTestItemInfo(String info) {
        TextView txt = findViewById(R.id.txtCurrentItem);
        if (txt != null) {
            txt.setText(info);

        }
    }

    private void updateTxtKeyInfo(String keyInfo) {
        TextView txt = findViewById(R.id.txtKeyInfo);
        if (txt != null) {
            txt.setText(keyInfo);
        }
    }

    private void updateTxtTips() {
        TextView txt = findViewById(R.id.txtTips);
        if (txt != null) {
            txt.setText(buildAgingTestTips());
        }
    }

    private void setStateEnabledAndInitStartTimeAbsolute() {

        boolean enabled = AgingTestItemAttr.isAgingTestEnabled(mContext);
        if (enabled) {
            return;
        }

        AgingTestItemAttr.setAgingTestEnabled(mContext, true);

        final long now = System.currentTimeMillis();

//        printStartAndExitTime();

        if (!AgingTestItemAttr.isAgingExitOk(mContext) && AgingTestItemAttr.isAgingKeepRecord(mContext)) {

            DebugLog.e("init all startTime with (now - (exitTime - startTime))");


            long startTime = AgingTestItemAttr.getAgingStartTimeAbsolute_ms(mContext);
            long exitTime = AgingTestItemAttr.getAgingExitTimeAbsolute_ms(mContext);

            AgingTestItemAttr.setAgingStartTimeAbsolute_ms(mContext, now - (exitTime - startTime));
            AgingTestItemAttr.setAgingExitTimeAbsolute_ms(mContext, now);

            for (AgingTestItemAttr attr : AgingTestItemAttr.values()) {
                if (attr.isTestOver(mContext)) {
                    continue;
                }

                long startTimeOfItem = attr.getStartTimeAbsolute_ms(mContext);

                attr.setStartTimeAbsolute_ms(mContext, now - (exitTime - startTimeOfItem));
                attr.setExitTimeAbsolute_ms(mContext, now);

            }

        } else {

//            DebugLog.e("init all startTime with now = " + now);
            DebugLog.e("init all startTime with now = " + new SimpleDateFormat("yyyy-MM-dd-HH-mm-sss", Locale.CHINA).format(now));

            AgingTestItemAttr.setAgingStartTimeAbsolute_ms(mContext, now);

            for (AgingTestItemAttr attr : AgingTestItemAttr.values()) {

                attr.setStartTimeAbsolute_ms(mContext, now);

            }
        }

    }


    private volatile boolean isExitAging = false;
    private final Object lock = new Object();

    private void exitAging(boolean keepRecord) {

        synchronized (lock) {
            if (isExitAging) {
                return;
            }
            isExitAging = true;

        }

        AgingTestItemAttr.setAgingExitTimeAbsolute_ms(mContext, System.currentTimeMillis());

        DebugLog.e("exitAging keepRecord = " + keepRecord);

        boolean ok = true;
        if (!keepRecord) {

            for (AgingTestItemBase item : agingTestItemList) {
                item.clearRecord();
            }

            AgingTestItemAttr.clearAgingAll(mContext);

            ok = false;

        } else {


            AgingTestItemAttr.setAgingExitOk(mContext, true);

            for (AgingTestItemBase item : agingTestItemList) {
                if (item.getAgingTestItemAttr() == null) {
                    continue;
                }
                if (!item.getAgingTestItemAttr().isTestOver(mContext)) {
                    ok = false;
                    AgingTestItemAttr.setAgingExitOk(mContext, false);
                    break;
                }
            }

            if (AgingTestItemAttr.isHardwareEmmcTestFailed(mContext)) {
                ok = false;
            }

            if (AgingTestItemAttr.getHardwareCpuFailCount(mContext) > 0) {
                ok = false;
            }

            if (EinkProperty.isErrorBootCount()) {
                ok = false;
            }

            if (!AgingTestItemAttr.isEmmcCpuTestOK(mContext)) {
                ok = false;
            }

            if (AgingTestItemAttr.getAbnormalShutdownCount(mContext) > 0) {
                ok = false;
            }

            if (AgingTestItemAttr.getTemperatureInvalidCount(mContext) > 0) {
                ok = false;
            }

            if (AgingTestItemAttr.getMemoryErrorCount(mContext) > 0) {
                ok = false;
            }

            //临时限制WiFi
            if (AgingTestItemAttr.getHardwareWifiErrorCount(mContext) > Constants.MAX_WIFI_FAILURES_ALLOWED) {
                ok = false;
            }
        }

        doDestroy();

        AgingTestItemAttr.setAgingKeepRecord(mContext, keepRecord);
        AgingTestItemAttr.setAgingTestEnabled(mContext, false);

        if (ok) {
            finishWithOK();
            StandbyUtil.setStandbyPng("老化完成 Pass");
        } else {
            finishWithFail();
            StandbyUtil.setStandbyPng("老化完成 Fail");
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        String status = getString(R.string.aging_test_current_keycode_status_down);
        String name = getStringByKeyCode(keyCode);

        updateTxtKeyInfo(getString(R.string.aging_test_keycode, keyCode, status, name));

        switch (keyCode) {
            case KeyEvent.KEYCODE_POWER:
                flagKeyDown |= FLAG_KEY_DOWN_POWER;
/*                if (!pm.isInteractive()) {
                    if (pm != null) {
                        pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK,
                                "factoryTest:ScreenOnTimer").acquire(5000);
                    }

                    KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
                    if (km != null) {
                        km.newKeyguardLock("TestCaseSleep").disableKeyguard();
                    }
                }*/
                break;
            case KeyEvent.KEYCODE_HOME:
                flagKeyDown |= FLAG_KEY_DOWN_HOME;
                break;
        }

        if ((flagKeyDown & flagKeyExit) == flagKeyExit) {
            showDialog();
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        String status = getString(R.string.aging_test_current_keycode_status_up);
        String name = getStringByKeyCode(keyCode);

        updateTxtKeyInfo(getString(R.string.aging_test_keycode, keyCode, status, name));

        switch (keyCode) {
            case KeyEvent.KEYCODE_POWER:
                flagKeyDown &= ~FLAG_KEY_DOWN_POWER;
                break;
            case KeyEvent.KEYCODE_HOME:
                flagKeyDown &= ~FLAG_KEY_DOWN_HOME;
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    @NonNull
    private String getStringByKeyCode(int keyCode) {
        String name = getString(R.string.aging_test_key_name_unknown);
        switch (keyCode) {
            case KeyEvent.KEYCODE_POWER:
                name = getString(R.string.aging_test_key_name_power);
                break;
            case KeyEvent.KEYCODE_HOME:
                name = getString(R.string.aging_test_key_name_home);
                break;
            case KeyEvent.KEYCODE_SLEEP:
                name = getString(R.string.aging_test_key_name_hall);
                break;
        }
        return name;
    }

    private void finishWithOK() {
        DebugLog.e("finishWithOK");
        setResult(RESULT_OK);
        ActivityCompat.finishAfterTransition(this);
    }

    private void finishWithFail() {
        DebugLog.e("finishWithFail");
        setResult(RESULT_CANCELED);
        ActivityCompat.finishAfterTransition(this);
    }

    private ViewDialogFragment dialogFragment;

    private void dismissDialog() {

        if (dialogFragment != null) {
            dialogFragment.dismiss();
            dialogFragment = null;
        }
    }

    private void showDialog() {

        try {
            if (dialogFragment == null) {
                final String title = getString(R.string.aging_test_dialog_title);
                final String msg = getString(R.string.aging_test_dialog_info);
                dialogFragment = ViewDialogFragment.newInstance(title, msg);
            }

            if (!dialogFragment.isShowing()) {

                dialogFragment.show(getFragmentManager(),
                        () -> myHandler.obtainMessage(MyHandler.MSG_EXIT_AGING, 1, 0).sendToTarget(),
                        () -> myHandler.obtainMessage(MyHandler.MSG_EXIT_AGING, 0, 0).sendToTarget());
            }

            myHandler.sendEmptyMessageDelayed(MyHandler.MSG_DISMISS_DIALOG, MyHandler.DELAY_DISMISS_DIALOG);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }

    }

    private void initPermission() {
        //如果无权限就申请然后回调，如果有权限就执行录音监听
        if (!isRecordGotPermission()) {
            //同时申请多个权限
            PermissionManager.getInstance(getApplicationContext()).execute(this,
                    android.Manifest.permission.RECORD_AUDIO,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE);

        }
    }

    private boolean isRecordGotPermission() {

        return (ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);

    }

    //如果有权限的话返回
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.getInstance(getApplicationContext()).
                onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    private void startLedCtrl() {
        if (!HtfyunBuildConfig.TEST_AGING_WITHOUT_SCREEN) {
            return;
        }
        if (!myHandler.hasMessages(MyHandler.MSG_LED_CTRL)) {
            myHandler.sendEmptyMessage(MyHandler.MSG_LED_CTRL);
        }
    }

    private void stopLedCtrl() {

        if (!HtfyunBuildConfig.TEST_AGING_WITHOUT_SCREEN) {
            return;
        }

        myHandler.removeMessages(MyHandler.MSG_LED_CTRL);
//        LedCtrl.setLed(false, LedCtrl.LedAttr.led_green, LedCtrl.LedAttr.led_red);
        LedCtrl_PX30.unControlLed();

    }

    private void startTemperatureCheck() {
        if (!myHandler.hasMessages(MyHandler.MSG_UPDATE_TEMPERATURE)) {
            myHandler.sendEmptyMessage(MyHandler.MSG_UPDATE_TEMPERATURE);
        }
    }

    private void stopTemperatureCheck() {
        myHandler.removeMessages(MyHandler.MSG_UPDATE_TEMPERATURE);
    }

    private void updateTemperature() {
//        int temp = BatteryInfo.getDeviceTemperature();
        int temp = batteryInfo.getBatteryTemperature();
        if (!BatteryInfo.isBatteryTemperatureInValidRange(temp)) {
            DebugLog.e("MSG_UPDATE_TEMPERATURE: " + temp + " is invalid");
            int count = AgingTestItemAttr.getTemperatureInvalidCount(mContext);
            AgingTestItemAttr.setTemperatureInvalidCount(mContext, ++count);
        }
        String tempInfo = "设备温度：" + temp;
        txtTemperature.setText(tempInfo);
    }

    private void updateTemperature(int temp) {
        if (!DeviceAttr.getRunningDeviceAttr().hasBatteryTemperatureCheck()) {
            txtTemperature.setVisibility(View.GONE);
            return;
        }
        if (!BatteryInfo.isBatteryTemperatureInValidRange(temp)) {
            DebugLog.e("updateTemperature: " + temp + " is invalid");
            int count = AgingTestItemAttr.getTemperatureInvalidCount(mContext);
            AgingTestItemAttr.setTemperatureInvalidCount(mContext, ++count);
        }
        String tempInfo = "设备温度：" + temp;
        txtTemperature.setText(tempInfo);
    }

    private static final class MyHandler extends Handler {

        private final static int MSG_TIME_TICK = 99;
        private final static int PERIOD_TIME_TICK = 1000;

        private final static int MSG_EXIT_AGING = 200;

        private final static int MSG_DISMISS_DIALOG = 300;
        private final static int DELAY_DISMISS_DIALOG = 10000;

        private final static int MSG_LED_CTRL = 1000;
        private final static int PERIOD_LED_CTRL = 800;

        private final static int MSG_UPDATE_TIPS = 1001;
        private final static int DELAY_UPDATE_TIPS = 1500;

        private final static int MSG_UPDATE_TEMPERATURE = 1002;
        private final static int MSG_UPDATE_TEMPERATURE_DELAY = 60 * 1000;

        private int ledOnCount = 0;

        private final WeakReference<AgingTestActivity> reference;

        public MyHandler(AgingTestActivity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            AgingTestActivity activity = reference.get();
            if (activity == null) {
                return;
            }

            switch (msg.what) {
                case MSG_UPDATE_TEMPERATURE:
                    activity.updateTemperature();
                    sendEmptyMessageDelayed(msg.what, MSG_UPDATE_TEMPERATURE_DELAY);
                    break;

                case MSG_DISMISS_DIALOG:
                    activity.dismissDialog();
                    break;

                case MSG_EXIT_AGING: {
                    boolean keep = msg.arg1 == 1;
                    activity.exitAging(keep);
                    break;
                }

                case MSG_LED_CTRL:

                    if (++ledOnCount > 10000) {
                        ledOnCount = 0;
                    }
//                    LedCtrl.setLed((0 == (ledOnCount % 2)), LedCtrl.LedAttr.led_green);
//                    LedCtrl.setLed(!(0 == (ledOnCount % 2)), LedCtrl.LedAttr.led_red);
                    if (0 == (ledOnCount % 2)) {
                        LedCtrl_PX30.setLed("R");
                        LedCtrl_PX30.setLed("g");
                        DebugLog.d("led set green");
                    } else {
                        LedCtrl_PX30.setLed("G");
                        LedCtrl_PX30.setLed("r");
                        DebugLog.d("led set red");
                    }

                    sendEmptyMessageDelayed(msg.what, PERIOD_LED_CTRL);

                    break;

                case MSG_TIME_TICK:
                    long tick = AgingTestItemAttr.getAgingTimeTick_ms(activity);
                    tick += PERIOD_TIME_TICK;
                    AgingTestItemAttr.setAgingTimeTick_ms(activity, tick);

                    AgingTestItemAttr.setAgingExitTimeAbsolute_ms(activity, System.currentTimeMillis());

                    if (!FTUtils.isInAgingTest(activity)) {
                        //外部原因导致他已经退出老化测试了, 比如在老化测试时, 发送清除老化测试数据的广播.
                        //延迟退出是为了避免跟正常退出时冲突.
                        DebugLog.e("Aging test is disabled, exit!!!");
                        activity.exitAging(true);

                    } else {

                        activity.periodicCheckItemTest();

                        sendEmptyMessageDelayed(msg.what, PERIOD_TIME_TICK);

                    }

                    break;
                case MSG_UPDATE_TIPS:
                    activity.updateTxtTips();
                    break;
            }
        }
    }

    //广播监听
    private void registerReceiver() {
        IntentFilter filter = new IntentFilter(PCCommand.PC_ACTION_SET_AGING_ITEM_TEST_OVER_RATIO);
        registerReceiver(myReceiver, filter);
    }

    private void unregisterReceiver() {
        unregisterReceiver(myReceiver);
    }

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action == null) {
                return;
            }

            if (action.equals(PCCommand.PC_ACTION_SET_AGING_ITEM_TEST_OVER_RATIO)) {
                myHandler.sendEmptyMessageDelayed(MyHandler.MSG_UPDATE_TIPS, MyHandler.DELAY_UPDATE_TIPS);
            }

        }
    };

    private final BatteryInfo.OnBatteryChangedListener onBatteryChangedListener =
            info -> {
                updateTemperature(info.getBatteryTemperature());

                if (info.getBatteryChargePlugType() == BatteryManager.BATTERY_PLUGGED_AC
                        || info.getBatteryChargePlugType() == BatteryManager.BATTERY_PLUGGED_USB) {

                    dismissDialogWhenChargeUnplug();

                    BatteryCurrentThresholdEnum thresholdEnum = null;
                    for (BatteryCurrentThresholdEnum e : BatteryCurrentThresholdEnum.values()) {
                        if (e.isInRange(info.getBatteryLevel())) {
                            thresholdEnum = e;
                            break;
                        }
                    }

                    boolean pass = (thresholdEnum != null &&
                            (info.getBatteryCurrent_mAh() >= thresholdEnum.getCurrent() || info.getBatteryCurrent_mAh() < 0));

                    if (!pass) {
                        showDialogWhenChargeCurrentFailed(info.getBatteryLevel(), info.getBatteryCurrent_mAh());
                    } else {
                        dismissDialogWhenChargeCurrentFailed();
                    }

                } else {
                    dismissDialogWhenChargeUnplug();
                    showDialogWhenChargeUnplug();
                }
            };


    private ViewDialogFragment dialogWhenChargeUnplug;

    private void dismissDialogWhenChargeUnplug() {

        if (dialogWhenChargeUnplug != null) {
            dialogWhenChargeUnplug.dismiss();
            dialogWhenChargeUnplug = null;
        }
    }

    private void showDialogWhenChargeUnplug() {

        dismissDialogWhenChargeCurrentFailed();

        if (dialogWhenChargeUnplug == null) {
            final String title = getString(R.string.battery_check_event);
            final String msg = getString(R.string.battery_check_unplug);
            dialogWhenChargeUnplug = ViewDialogFragment.newInstance(title, msg, true);
        }

        if (!dialogWhenChargeUnplug.isShowing()) {
            try {
                dialogWhenChargeUnplug.show(getFragmentManager());
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }

    }

    private ViewDialogFragment dialogWhenChargeCurrentFailed;

    private void dismissDialogWhenChargeCurrentFailed() {

        if (dialogWhenChargeCurrentFailed != null) {
            dialogWhenChargeCurrentFailed.dismiss();
            dialogWhenChargeCurrentFailed = null;
        }
    }

    private void showDialogWhenChargeCurrentFailed(int level, int current) {

        dismissDialogWhenChargeCurrentFailed();

        final String title = getString(R.string.battery_check_charge_current);
        final String msg = getString(batteryInfo.getBatteryCapacity_mAh() >= Constants.BATTERY_CAPACITY_THRESHOLD
                ? R.string.battery_check_charge_current_condition
                : R.string.battery_check_charge_current_condition_low, level, current);
        dialogWhenChargeCurrentFailed = ViewDialogFragment.newInstance(title, msg, true);


        dialogWhenChargeCurrentFailed.show(getFragmentManager());

    }

    private void doubleClick() {
        //每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //为数组最后一位赋值
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
            boolean isMute = SystemProperties.getBoolean(Constants.FT_AGING_MUTE, false);
            VolumeUtils.setVolume(AudioManager.STREAM_MUSIC, isMute ? Constants.AGING_VOLUME : 0, 0);
            SystemProperties.set(Constants.FT_AGING_MUTE, isMute ? "false" : "true");
            mHits = new long[COUNTS];
            showToast(isMute ? getString(R.string.enabled_speaker) : getString(R.string.disabled_speaker), Gravity.TOP);
        }
    }

}
